package com.weizai.carshop.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weizai.carshop.common.context.BaseContext;
import com.weizai.carshop.common.properties.JwtProperties;
import com.weizai.carshop.common.utils.JwtUtil;
import com.weizai.carshop.mapper.LoginMapper;
import com.weizai.carshop.model.dto.LoginDto;
import com.weizai.carshop.model.entiity.AdminUserList;
import com.weizai.carshop.model.vo.LoginVo;
import com.weizai.carshop.model.vo.UserInfoVo;
import com.weizai.carshop.service.LoginService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class LoginServerImpl extends ServiceImpl<LoginMapper, AdminUserList> implements LoginService {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private LoginMapper loginMapper;

    /**
     * 登录验证
     * @param loginDto
     * @return
     */
    @Override
    public LoginVo login(LoginDto loginDto) {
        LambdaQueryWrapper<AdminUserList> loginVoLambdaQueryWrapper = new LambdaQueryWrapper();
        loginVoLambdaQueryWrapper.eq(AdminUserList::getUsername,loginDto.getUsername());
        AdminUserList info = loginMapper.selectOne(loginVoLambdaQueryWrapper);
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId",info.getId());
        claims.put("username",info.getUsername());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
       LoginVo loginVo = LoginVo.builder()
               .token(token).build();
        return loginVo;
    }

    /**
     * 获取用户信息
     * @return
     */
    @Override
    public UserInfoVo getUserInfo() {
        Long currentId = BaseContext.getCurrentId();
        AdminUserList userInfo = loginMapper.selectById(currentId);
        UserInfoVo userInfoVo = UserInfoVo.builder()
                .id(userInfo.getId())
                .username(userInfo.getUsername())
                .nickname(userInfo.getNickname())
                .state(userInfo.getState())
                .createTime(userInfo.getCreateTime())
                .updateTime(userInfo.getUpdateTime())
                .build();
        return userInfoVo;

    }
}
